use std::sync::mpsc;
use std::thread;

use futures::{select, FutureExt};
use honeybee::prelude::*;
use honeybee::Result;
use rand::prelude::*;

use crate::connect::Connect;

pub fn run(shutdown_tx: mpsc::SyncSender<&'static str>) -> Addr<ShutdownActor> {
    let (tx, rx) = mpsc::sync_channel(1);
    let _ = thread::Builder::new()
        .name("async_main_thread".into())
        .spawn(move || {
            block_on(async move {
                let shutdown_addr = honeybee::prelude::init().await.unwrap();
                tx.send(shutdown_addr.clone()).unwrap();
                select! {
                    result = async_main().fuse() => {
                        if let Err(err) = result {
                            error!("async_main err:{}", err);
                        }
                    }
                    _ = shutdown_addr.wait_for_stop().fuse() => {}
                }
            });
            info!("async_main thread stoped");
            let _ = shutdown_tx.send("async_main exit");
        });
    rx.recv().unwrap()
}
async fn async_main() -> Result<()> {
    /*
    for _ in 0..1 {
        let _ = Connect::new(&format!("user_{}", 0), "127.0.0.1:19680")
            .start()
            .await?;
    }
    */
    for _ in 0..100 {
        let mut rng = rand::thread_rng();
        let account;
        let endpoint;
        let id = rng.gen_range(0..10);
        account = format!("user_{}", id);
        /*
        if rng.gen_bool(0.5) {
        account = "user_0";
        } else {
        account = "user_1";
        }
        */
        if rng.gen_bool(0.5) {
            endpoint = "127.0.0.1:19680";
        } else {
            endpoint = "127.0.0.1:19681";
        }
        let _ = Connect::new(&account, &endpoint).start().await?;
    }
    futures::future::pending::<()>().await;
    Ok(())
}
